package com.mall.Inteceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor{
	private static Map<String,Long> map=new HashMap<String,Long>();
	/**
	 * contorller方法执行之完成后执行,可做全局异常处理和日志.
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}
	/**
	 * contorller方法执行之后,返回ModelAndView之前执行,可做全局参数的设置
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@Override
	
	/**
	 * contorller方法执行之前执行,可做登录验证
	 */
	public boolean preHandle(HttpServletRequest hsr, HttpServletResponse arg0, Object arg2) throws Exception {
		/*Date date=new Date();
		String ip=this.getUserIpAddr(hsr);
		Long fst=map.get(ip);
		Long now=date.getTime();
		if(fst==null){
			map.put(ip,now);
		}else{
			if(now-fst<1000){
				map.put(ip,now);
				return false;
			}
			map.put(ip,now);
		}*/
		return true;
	}
	 private String getUserIpAddr(HttpServletRequest request) {
           String ip = request.getHeader("x-forwarded-for");
           if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getHeader("Proxy-Client-IP");
           }
           if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getHeader("WL-Proxy-Client-IP");
           }
           if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getRemoteAddr();
           }
           return ip;
    }

}
